//
//  SEGSettleApplyViewModel.m
//  SEGModel
//
//  Created by 梁学彰 on 2020/11/25.
//

#import "SEGSettleApplyViewModel.h"

@implementation SEGSettleApplyViewModel {
    NSString *_imagePath;
}


- (RACSignal *)sendSettleApplyRequestWithUploadArr:(NSArray *)uploadArr {
    return [RACSignal concat:@[[self upLoadImagesWithUploadArr:uploadArr],[self requestSettleApply]]];
}

- (RACSignal *)upLoadImagesWithUploadArr:(NSArray *)uploadArr {

    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {

        
        // 上传图片
        [subscriber sendNext:@"1"];
        if(uploadArr.count > 0) {
            [[SEGMultipartfileuploadManager sharedManager] requestMultipartfileuploadWithImage:uploadArr progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if(isSuccessed) {
                    NSArray *data = result[@"data"];
                    NSMutableString *imagePath = [NSMutableString string];
                    for (NSString *subImage in data) {
                        [imagePath appendString:subImage];
                        [imagePath appendString:@","];
                    }
                    // 去掉最后一个逗号
                    if (imagePath.length > 0) {
                        imagePath = [[imagePath substringToIndex:imagePath.length - 1] mutableCopy];
                    }
                    self->_imagePath = imagePath;
                    [subscriber sendCompleted];
                }else {
                    [subscriber sendNext:@"0"];
                    [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                }
            }];
        } else {
            self->_imagePath = @"";
            [subscriber sendCompleted];
        }
        
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)requestSettleApply {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        [SEGSettleApplyManager requestSettleApplyWithName:self.nameTextFieldString tel:self.phoneTextFieldString industry:self.industryTextFieldString companyName:self.companyTextFieldString imagePath:self->_imagePath finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            [subscriber sendNext:@"0"];
            if (!isSuccessed) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:errorMessage}]];
                return;
            } else {
                [subscriber sendCompleted];
            }
        }];
        
        
        return nil;
    }];
    return signal;
}

@end
